// 选择器
function E(selector) {
    return document.querySelector(selector);
}

// Blod 二进制大容器，图片与语音文件 ； 获得资源（请求资源）
function fetchBlob(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url);
    xhr.responseType = 'blob'; //返回响应的类型
    xhr.onload = function () {
        if(xhr.status==200){ 
            callback(this.response);
        }
        
    };
    xhr.onerror = function () {
        alert('Failed to fetch ' + url);
    };
    xhr.send();
}

// 播放arm二进制文件--amr语音格式的播放
function playAmrBlob(blob, callback) {
    readBlob(blob, function (data) {
        playAmrArray(data);
    });
}

// 读取二进制文件
function readBlob(blob, callback) {
    var reader = new FileReader();
    reader.onload = function (e) {
        var data = new Uint8Array(e.target.result);
        callback(data);
    };
    reader.readAsArrayBuffer(blob);
}

// amr语音文件转码
function playAmrArray(array) {
    var samples = AMR.decode(array);
    if (!samples) {
        alert('Failed to decode!');
        return;
    }
    playPcm(samples);
}

var src = null;
function playPcm(samples) {
    var ctx = getAudioContext();
    src = ctx.createBufferSource();
    var buffer = ctx.createBuffer(1, samples.length, 8000);
    if (buffer.copyToChannel) {
        buffer.copyToChannel(samples, 0, 0)
    } else {
        var channelBuffer = buffer.getChannelData(0);
        channelBuffer.set(samples);
    }

    src.buffer = buffer;
    src.connect(ctx.destination);
    src.start();
}

// 创建AudioContext对象，音频处理
var gAudioContext = new AudioContext();
function getAudioContext() {
    if (!gAudioContext) {
        gAudioContext = new AudioContext();
    }
    return gAudioContext;
}


// 将audio语音格式转成amr语音格式并播放
function convertAudioBlobToAmr(blob) {
    readBlob(blob, function (data) {
        var ctx = getAudioContext();
        // decodeAudioData()方法可用于异步解码音频文件中的 ArrayBuffer
        ctx.decodeAudioData(data.buffer, function (audioBuffer) {
            var pcm;
            if (audioBuffer.copyFromChannel) {
                pcm = new Float32Array(audioBuffer.length);
                audioBuffer.copyFromChannel(pcm, 0, 0);
            } else {
                pcm = audioBuffer.getChannelData(0);
            }
            var amr = AMR.encode(pcm, audioBuffer.sampleRate, 7);
            playAmrArray(amr);
        });
    });
}

// base64格式的语音播放
function playAmrToWav(amrStr) {
    if (null != src) {
        src.stop();
        src = null;
    }
    // atob 方法解码中文字符乱码问题
    var amrStr = window.atob(amrStr),
        result = new Uint8Array(amrStr.length);
    for (var i = 0, l = amrStr.length; i < l; i++) {
        result[i] = amrStr.charCodeAt(i)
    }
    playAmrArray(result);
}

// 将amr语音格式转成audio语音格式，并播放
function convertAmrBlobToWav(blob) {
    readBlob(blob, function (data) {
        var buffer = AMR.toWAV(data);
        // E('pre').textContent = toHex(buffer);  //用于将转码的数据展示的页面中
        var url = URL.createObjectURL(new Blob([buffer], {type: 'audio/x-wav'}));
       
        // Play wav buffer
        var audio = new Audio(url);
        audio.onloadedmetadata = audio.onerror = function () {
            URL.revokeObjectURL(url);
        };
        audio.play();
    });
}
function toHex(buffer) {
    var str = '';
    for (var i = 0; i < buffer.length; i++) {
        var s = buffer[i].toString(16);
        if (s.length == 1) {
            s = '0' + s;
        }
        str += s;
        if (i % 16 == 15) { // print 16 bytes per line
            str += '\n'
        } else if (i % 2 == 1) { // add a space seperator every two bytes.
            str += ' ';
        }
    }
    return str;
}


